package cate.game.server.cli.mock;

import cate.game.client.msg.GameMsg;
import cate.game.client.msg.id.MsgIdA;
import cate.game.client.msg.id.MsgIdBLogin;
import cate.game.role.login.msg.LoginStartResp;
import cate.game.role.login.msg.RoleCreateResp;
import cate.game.server.cli.MsgDecode;
import cate.game.server.cli.mock.msg.MockLoginStartReq;
import easy.socket.client.ClientProperties;
import easy.socket.handler.WsClientHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MockCliHandler extends WsClientHandler {

    private MockCli parent;

    public MockCliHandler(ClientProperties properties, MockCli parent) {
        super(properties);
        this.parent = parent;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        super.channelActive(ctx);
        log.info("模拟客户端 channelActive");
        TextWebSocketFrame textFrame = new TextWebSocketFrame("啊啊IamMockCli-channelActive");
        ctx.writeAndFlush(textFrame);
    }

    @Override
    protected void onConnected(ChannelHandlerContext ctx, Object msg) {
        super.onConnected(ctx, msg);
        log.info("模拟客户端 onConnected");
        this.parent.netty.setCtx(ctx);
        MockLoginStartReq req = new MockLoginStartReq();
        req.token = parent.token;
        req.roleId = parent.roleId;
        req.sendNow(ctx);
    }

    @Override
    protected void handleBinaryWebSocketFrame(ChannelHandlerContext ctx, BinaryWebSocketFrame frame) {
        //super.handleBinaryWebSocketFrame(ctx, frame);
        GameMsg msg = MsgDecode.decode(frame, ctx);
        log.info("MockCli收到消息 a={},b={}", msg.idA, msg.idB);
        if(msg.idA == MsgIdA.LOGIN) {
            if(msg.idB == MsgIdBLogin.START_RESP.b) {
                parent.onLoginStartResp(msg.decodeJson(LoginStartResp.class));
            } else if(msg.idB == MsgIdBLogin.CREATE_ROLE_RESP.b) {
                parent.onRoleCreateResp(msg.decodeJson(RoleCreateResp.class));
            }
        } else if(msg.idA == MsgIdA.TRAIN) {

        }
    }
}
